package handler

import (
	"fmt"

	"github.com/go-playground/validator"
	"github.com/kataras/iris/v12"
)

type validationError struct {
	ActualTag string `json:"tag"`
	Namespace string `json:"namespace"`
	Kind      string `json:"kind"`
	Type      string `json:"type"`
	Value     string `json:"value"`
	Param     string `json:"param"`
}

func wrapValidationErrors(errs validator.ValidationErrors) []validationError {
	validationErrors := make([]validationError, 0, len(errs))
	for _, validationErr := range errs {
		validationErrors = append(validationErrors, validationError{
			ActualTag: validationErr.ActualTag(),
			Namespace: validationErr.Namespace(),
			Kind:      validationErr.Kind().String(),
			Type:      validationErr.Type().String(),
			Value:     fmt.Sprintf("%v", validationErr.Value()),
			Param:     validationErr.Param(),
		})
	}

	return validationErrors
}

func ArgumentErrorHandle(err error, ctx iris.Context) {
	if err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok {
			// Wrap the errors with JSON format, the underline library returns the errors as interface.
			validationErrors := wrapValidationErrors(errs)

			// Fire an application/json+problem response and stop the handlers chain.
			ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem().
				Title("Validation error").
				Detail("One or more fields failed to be validated").
				Key("errors", validationErrors))
			return
		}
		ctx.JSON(iris.Map{"code": iris.StatusBadRequest, "message": iris.StatusText(iris.StatusBadRequest), "data": err.Error()})
		return
	}

}

/*
 * 自定义jwt错误处理函数
 */

func JwtOnError(ctx iris.Context, err error) {
	if err == nil {
		return
	}
	ctx.JSON(iris.Map{"code": iris.StatusUnauthorized, "message": err.Error()})
	return
}
